<?
	include_once "libhtml.php";
	include_once "libsession.php";
	include_once "constants.php";
	include_once "../dbconfig.php";
	
	$targetid = $_POST["targetid"];
	$redirecturl = $_POST["redirecturl"];
	
	// figure out what we're supposed to do
	if (isset($_POST["action"]))
	{
		$action = $_POST["action"];
		
		if ($action == "login")
		{
			$userid = login($_POST["UserName"], $_POST["Password"]);
			
			if ($userid > 0)
			{
				// login successful
				$redirecturl .= "?userid=" . $userid;
			}
			else
			{
				// login fail
				$redirecturl = "index.php";
			}
		}
		else if ($action == "adddocument")
		{	
			$sql = "INSERT INTO Document(Title, OwnerId) VALUES ('Untitled', $targetid);";
			
			insert_db($sql);
		}
		else if ($action == "updatedocument")
		{
			$title = $_POST['Title'];
			$datedue = $_POST['DateDue'];
			$templateid = $_POST["WorkflowTemplateId"];
			$oldtemplateid = $_POST["oldtemplateid"];
			$currentfile = $_POST["CurrentFile"];
			
			// upload the file
			$file = upload_file($targetid);
			
			$sql = "UPDATE Document SET Title='$title', ";
			
			// handle dates
			if ($datedue == null || $datedue=='')
			{
				$sql .= " DateDue=null, ";
			}
			else
			{
				$sql .= " DateDue='$datedue', ";
			}
			
			if ($templateid == null || $templateid=="0" || $templateid==0)
			{
				$sql .= " WorkflowTemplateId=null, WorkflowStepId=null, ";
				
				// clear the actions
				query_db("DELETE FROM ScheduledAction WHERE DocumentId=$targetid");
			}
			
			if ($file["path"] == null || $file["path"]=='')
			{
				if ($currentfile == null && $currentfile == '')
					$sql .= " FilePath=null, ";	
			}
			else
			{
				$filepath = str_replace("\\", "\\\\", $file["path"]);
				$sql .= " FilePath='$filepath', ";
			}
			
			if ($file["name"] == null || $file["name"] == '')
			{
				if ($currentfile == null || $currentfile == '')
					$sql .= " FileName=null ";
			}
			else
			{
				$filename = $file["name"];
				$sql .= " FileName='$filename' ";
			}
			
			$sql .= " WHERE Id=$targetid";
					
			//echo $sql;
			query_db($sql);
			
			// now that flat data is changed, handle wft changes
			if ($oldtemplateid != $templateid && $templateid != null && $templateid > 0)
			{
				changewft($targetid, $templateid);
			}
		}
		else if ($action == "deletedocument")
		{
			$sql = "DELETE FROM Document WHERE Id=$targetid";
			
			query_db($sql);
			
			$sql = "DELETE FROM ScheduledEvent WHERE DocumentId=$targetid";
			
			query_db($sql);
		}
		else if ($action == "downloadfile")
		{
			// fetch the file info from the document
			$sql = "SELECT FileName, FilePath FROM Document WHERE Id=$targetid LIMIT 1";
			
			$fileinfo = query_db($sql);
			$fileinfo = mysql_fetch_array($fileinfo, MYSQL_ASSOC);
			
			// download the file
			downloadFile($fileinfo["FilePath"], $fileinfo["FileName"]);
		}
		else if ($action == "addtemplate")
		{
			$sql = "INSERT INTO WorkflowTemplate(Name) VALUES ('Untitled');";
			insert_db($sql);	
		}
		else if ($action == "deletetemplate")
		{
			// make sure it's not in use first
			
			$sql = "SELECT COUNT(1) AS Occurs FROM Document WHERE WorkflowTemplateId=$targetid";
			$results = query_db($sql);
			
			$row = mysql_fetch_array($results, MYSQL_ASSOC);
			$count = $row["Occurs"];
			if ($count > 0)
			{
				// TODO: give exception
				return;
			}
			
			// delete appropriate scheduled actions
			$sql = "DELETE sa
					FROM ScheduledAction sa
					INNER JOIN WorkflowAction wa ON wa.Id=sa.ActionId
					INNER JOIN WorkflowStep ws ON ws.Id=wa.StepId
					INNER JOIN WorkflowTemplate wt ON wt.Id=ws.TemplateId
					WHERE wt.Id=$targetid";
					
			query_db($sql);
					
			// first delete all actions
			$sql = "DELETE wa 
					FROM WorkflowAction wa
					INNER JOIN WorkflowStep ws ON ws.Id=wa.StepId
					INNER JOIN WorkflowTemplate wt ON wt.Id=ws.TemplateId
					WHERE wt.Id=$targetid";
			query_db($sql);
			
			// delete the step now
			$sql = "DELETE ws 
					FROM WorkflowStep ws
					INNER JOIN WorkflowTemplate wt ON wt.Id=ws.TemplateId
					WHERE wt.Id=$targetid";
			query_db($sql);
			
			// delete the template now
			$sql = "DELETE FROM WorkflowTemplate WHERE Id=$targetid";
			query_db($sql);
		}
		else if ($action == "addstep")
		{
			$sql = "INSERT INTO WorkflowStep(TemplateId) VALUES ($targetid);";

			insert_db($sql);
		}
		else if ($action == "updatestep")
		{
			// get the data
			$name = $_POST["Name"];
			$islocked = $_POST["IsLocked"];
			
			if ($islocked != "locked")
			{
				$islocked = 0;	
			}
			else
			{
				$islocked = 1;
			}
			
			// update the db
			$sql = "UPDATE WorkflowStep SET Name='$name', IsLocked=$islocked WHERE Id=$targetid";
			
			query_db($sql);
		}
		else if ($action == "deletestep")
		{
			// make sure the step is not in use right now
			$sql = "SELECT COUNT(1) AS NUM FROM Document WHERE WorkflowStepId=$targetid";
			
			$result = query_db($sql);
			$row = mysql_fetch_array($result, MYSQL_ASSOC);
			if ($row["NUM"] > 0)
			{
				// TODO: raise an error
				return;
			}
			
			
			// delete appropriate scheduled actions
			$sql = "DELETE sa
					FROM ScheduledAction sa
					INNER JOIN WorkflowAction wa ON wa.Id=sa.ActionId
					INNER JOIN WorkflowStep ws ON ws.Id=wa.StepId
					WHERE ws.Id=$targetid";
					
			query_db($sql);
			
			// first delete all actions
			$sql = "DELETE wa 
					FROM WorkflowAction wa
					INNER JOIN WorkflowStep ws ON ws.Id=wa.StepId
					WHERE ws.Id=$targetid";
			query_db($sql);
			
			// delete the step now
			$sql = "DELETE FROM WorkflowStep WHERE Id=$targetid";
			query_db($sql);
		}
		else if ($action == "addevent")
		{
			$sql = "INSERT INTO WorkflowEvent(StepId) VALUES ($targetid);";
			
			insert_db($sql);
		}
		else if ($action == "updateevent")
		{
			// get the data
			$type = $_POST["Type"];
			$date = $_POST["ParamDate"];
			
			if ($date == null || $date=='')
				$sql = "UPDATE WorkflowEvent SET Type=$type, ParamDate=null WHERE Id=$targetid";
			else
				$sql = "UPDATE WorkflowEvent SET Type=$type, ParamDate='$date' WHERE Id=$targetid";

			
			query_db($sql);
		}
		else if ($action == "deleteevent")
		{
			// first delete actions
			$sql = "DELETE FROM WorkflowAction WHERE EventId=$targetid";
			
			query_db($sql);
			
			// now delete event
			$sql = "DELETE FROM WorkflowEvent WHERE Id=$targetid";
			
			query_db($sql);
		}
		else if ($action == "addaction")
		{
			$sql = "INSERT INTO WorkflowAction(StepId) VALUES ($targetid);";
			
			insert_db($sql);	
		}
		else if ($action == "updateaction")
		{
			// get the data
			$eventtype = $_POST["EventType"];
			$eventparamdate = $_POST["EventParamDate"];
			$type = $_POST["Type"];
			$paramstepid = $_POST["ParamStepId"];
			$paramuserid = $_POST["ParamUserId"];
			$paramemailmsg = $_POST["ParamEmailMsg"];
			
			if ($paramstepid == 0)
				$paramstepid = "null";
				
			if ($paramuserid == 0)
				$paramuserid = "null";
				
			// handle date
			$sqldate = "";
			if ($eventparamdate == null || $eventparamdate=='')
			{
				$sqldate .= " EventParamDate=null, ";
			}
			else
			{
				$sqldate .= " EventParamDate='$eventparamdate', ";
			}
			
			
			$sql = "UPDATE WorkflowAction SET 
							EventType=$eventtype,";
			$sql .= 		$sqldate;
			$sql .= "		Type=$type,
							ParamStepId=$paramstepid,
							ParamUserId=$paramuserid,
							ParamEmailMsg='$paramemailmsg'
					WHERE Id=$targetid";
			//echo $sql;
			query_db($sql);
				
		}
		else if ($action == "deleteaction")
		{
			$sql = "DELETE sa
					FROM ScheduledAction sa
					INNER JOIN WorkflowAction wa ON wa.Id=sa.ActionId
					WHERE wa.Id=$targetid";
			query_db($sql);
			
			$sql = "DELETE FROM WorkflowAction WHERE Id=$targetid";
			
			query_db($sql);
		}
		else if ($action == "executeaction")
		{
			execute_wf_action($_POST["docid"], $targetid);
		}
	}
	
	function upload_file($docid)
	{
		// TODO: raise error
		
		$file = array("name" => null, "path" => null);
		
		if ($_FILES["file"]["error"] > 0)
			return $file;
		
		if ($_FILES["file"]["name"] == null)
			return $file;
			
		$dir = UPLOAD_DIRECTORY . "$docid\\";
		
		if (false)
		{
			// debug stuff, don't execute
			echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    		echo "Type: " . $_FILES["file"]["type"] . "<br />";
    		echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    		echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
		}	
		
    	$filepath = $dir . $_FILES["file"]["name"];
    			
    	if (file_exists($filepath))
      	{
	    	// delete the file since we don't know if it was edited
      		unlink($filepath);
      	}
   
      	if (!file_exists($dir))
      	{
	    	// create the directory
      		mkdir($dir);
  		}
	      		
  		// now upload the actual file
      	move_uploaded_file($_FILES["file"]["tmp_name"],$filepath);
      	
      	$file = array("name" => $_FILES["file"]["name"], "path" => $filepath);
      	return $file;
	}
	
	// change the workflow template for a document
	function changewft($docid, $templateid)
	{
		if ($docid == null || $docid == 0 || $docid == "0")
			return;
			
		// update the template on the document
		$sql = "UPDATE Document SET WorkflowTemplateId=$templateid
				WHERE Id=$docid";
				
		query_db($sql);
		
		// get the new stepid, which is the first one in a template
		$sql = "SELECT Id FROM WorkflowStep WHERE TemplateId=$templateid
				ORDER BY Id LIMIT 1;";
				
		$result = query_db($sql);
		if ($result == null || mysql_num_rows($result) == 0)
		{
			// clear the step
			changestep($docid, 0);
			return;	
		}
		
		$step = mysql_fetch_array($result, MYSQL_ASSOC);
		$stepid = $step["Id"];
		
		mysql_free_result($result);
		
		// now change the step
		changestep($docid, $stepid);
	}
	
	// change workflow steps
	function changestep($docid, $stepid)
	{
		if ($docid == null || $docid == "" || $docid == 0)
			return;
			
		if ($stepid == null || $stepid == "" || $stepid == "0" || $stepid == 0)
		{
			// clear the step
			$sql = "UPDATE Document SET WorkflowStepId=null WHERE Id=$docid";
			query_db($sql);
			
			// clear its scheduled actions
			$sql = "DELETE FROM ScheduledAction WHERE DocumentId=$docid";
			
			query_db($sql);
			
			return;
		}
			
		// change the step on the document
		$sql = "UPDATE Document SET WorkflowStepId=$stepid WHERE Id=$docid";
		query_db($sql);
		
		// clear its scheduled actions
		$sql = "DELETE FROM ScheduledAction WHERE DocumentId=$docid";
		query_db($sql);
		
		// add new scheduled actions
		$sql = "INSERT INTO ScheduledAction (DocumentId, ActionId, Date)
				SELECT $docid, wa.Id, DATE_ADD(d.DateDue, INTERVAL wa.EventParamDate Day) FROM WorkflowAction wa
				INNER JOIN Document d ON d.Id=$docid
				WHERE wa.EventParamDate IS NOT NULL AND d.DateDue IS NOT NULL AND StepId=$stepid AND EventType=" . WF_EVENT_TYPE_DatePast;
		
		query_db($sql);
			
		// execute step-start actions
		$sql = "SELECT Id FROM WorkflowAction WHERE StepId=$stepid AND EventType=" . WF_EVENT_TYPE_StepStart;
		$actions = query_db($sql);

		if ($actions == null || mysql_num_rows($actions) == 0)
			return;
		
		while ($action = mysql_fetch_array($actions, MYSQL_ASSOC))
		{
			execute_wf_action($docid, $action["Id"]);	
		}
	}
	
	// executes a single workflow action
	function execute_wf_action($docid, $actionid)
	{
		if ($actionid == null || $actionid == 0)
			return;
			
		// get action details
		$sql = "SELECT Type, ParamStepId, ParamUserId, ParamEmailMsg
				FROM WorkflowAction WHERE Id=$actionid LIMIT 1;";
		$result = query_db($sql);
		
		if (mysql_num_rows($result) == 0)
			return;
			
		$action = mysql_fetch_array($result, MYSQL_ASSOC);
		
		if ($action == null)
			return;
			
		// what kind of action is it?
		if ($action["Type"] == WF_ACTION_TYPE_ChangeOwner)
		{
			// change the owner on the document
			$userid = $action["ParamUserId"];
			if ($userid != null && $userid != "" && $userid != "0" && $userid > 0)
			{
				$sql = "UPDATE Document SET OwnerId=$userid WHERE Id=$docid";
				query_db($sql);
			}
		}
		else if ($action["Type"] == WF_ACTION_TYPE_SendEmail)
		{
			// send an email
			Send_Email($action["ParamUserId"], $action["ParamEmailMsg"]);
		}
		else if ($action["Type"] == WF_ACTION_TYPE_Navigate)
		{
			// change the step
			$stepid = $action["ParamStepId"];
			changestep($docid, $stepid);
		}
	}
	
	function Send_Email($toid, $msg)
	{
		if ($userid == null || $userid == "" || $userid == "0" || $msg == null || $msg == "")
			return;
			
		// get user's email address
		$sql = "SELECT Email FROM User WHERE Id=$toid LIMIT 1;";
		$result = query_db($sql);
		if (mysql_num_rows($result) == 0)
			return;
			
		$row = mysql_fetch_array($result, MYSQL_ASSOC);
		$emailaddress = $row["Email"];
		
		// todo: send the actual email	
	}
	
	function downloadFile($fileLocation,$fileName,$maxSpeed = 100,$doStream =
false)
	{ 
	    if (connection_status()!=0) return(false); 
	    $extension = strtolower(end(explode('.',$fileName))); 
	
	    /* List of File Types */ 
	    $fileTypes['swf'] = 'application/x-shockwave-flash'; 
	    $fileTypes['pdf'] = 'application/pdf'; 
	    $fileTypes['exe'] = 'application/octet-stream'; 
	    $fileTypes['zip'] = 'application/zip'; 
	    $fileTypes['doc'] = 'application/msword'; 
	    $fileTypes['xls'] = 'application/vnd.ms-excel'; 
	    $fileTypes['ppt'] = 'application/vnd.ms-powerpoint'; 
	    $fileTypes['gif'] = 'image/gif'; 
	    $fileTypes['png'] = 'image/png'; 
	    $fileTypes['jpeg'] = 'image/jpg'; 
	    $fileTypes['jpg'] = 'image/jpg'; 
	    $fileTypes['rar'] = 'application/rar';     
	     
	    $fileTypes['ra'] = 'audio/x-pn-realaudio'; 
	    $fileTypes['ram'] = 'audio/x-pn-realaudio'; 
	    $fileTypes['ogg'] = 'audio/x-pn-realaudio'; 
	     
	    $fileTypes['wav'] = 'video/x-msvideo'; 
	    $fileTypes['wmv'] = 'video/x-msvideo'; 
	    $fileTypes['avi'] = 'video/x-msvideo'; 
	    $fileTypes['asf'] = 'video/x-msvideo'; 
	    $fileTypes['divx'] = 'video/x-msvideo'; 
	
	    $fileTypes['mp3'] = 'audio/mpeg'; 
	    $fileTypes['mp4'] = 'audio/mpeg'; 
	    $fileTypes['mpeg'] = 'video/mpeg'; 
	    $fileTypes['mpg'] = 'video/mpeg'; 
	    $fileTypes['mpe'] = 'video/mpeg'; 
	    $fileTypes['mov'] = 'video/quicktime'; 
	    $fileTypes['swf'] = 'video/quicktime'; 
	    $fileTypes['3gp'] = 'video/quicktime'; 
	    $fileTypes['m4a'] = 'video/quicktime'; 
	    $fileTypes['aac'] = 'video/quicktime'; 
	    $fileTypes['m3u'] = 'video/quicktime'; 
	
	    $contentType = $fileTypes[$extension]; 
	     
	     
	    header("Cache-Control: public"); 
	    header("Content-Transfer-Encoding: binary\n"); 
	    header('Content-Type: $contentType'); 
	
	    $contentDisposition = 'attachment'; 
	     
	    if($doStream == true){ 
	        /* extensions to stream */ 
	        $array_listen = array('mp3','m3u','m4a','mid','ogg','ra','ram','wm', 
	        'wav','wma','aac','3gp','avi','mov','mp4','mpeg','mpg','swf','wmv','divx','asf');
	        if(in_array($extension,$array_listen)){  
	            $contentDisposition = 'inline'; 
	        } 
	    } 
	
	    if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) { 
	        $fileName= preg_replace('/\./', '%2e', $fileName,
	substr_count($fileName, '.') - 1); 
	        header("Content-Disposition: $contentDisposition;
	filename=\"$fileName\""); 
	    } else { 
	        header("Content-Disposition: $contentDisposition;
	filename=\"$fileName\""); 
	    } 
	     
	    header("Accept-Ranges: bytes");    
	    $range = 0; 
	    $size = filesize($fileLocation); 
	     
	    if(isset($_SERVER['HTTP_RANGE'])) { 
	        list($a, $range)=explode("=",$_SERVER['HTTP_RANGE']); 
	        str_replace($range, "-", $range); 
	        $size2=$size-1; 
	        $new_length=$size-$range; 
	        header("HTTP/1.1 206 Partial Content"); 
	        header("Content-Length: $new_length"); 
	        header("Content-Range: bytes $range$size2/$size"); 
	    } else { 
	        $size2=$size-1; 
	        header("Content-Range: bytes 0-$size2/$size"); 
	        header("Content-Length: ".$size); 
	    } 
	         
	    if ($size == 0 ) { die('Zero byte file! Aborting download');} 
	    set_magic_quotes_runtime(0);  
	    $fp=fopen("$fileLocation","rb"); 
	     
	    fseek($fp,$range); 
	   
	    while(!feof($fp) and (connection_status()==0)) 
	    { 
	        set_time_limit(0); 
	        print(fread($fp,1024*$maxSpeed)); 
	        flush(); 
	        ob_flush(); 
	        sleep(1); 
	    } 
	    fclose($fp); 
	            
	    return((connection_status()==0) and !connection_aborted()); 
	}  
	
	// redirect back
	header("Location: " . $redirecturl);
	
?>